package com.ruiysoft.controller.mdse;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruiysoft.controller.anchor.Anchor;
import com.ruiysoft.controller.anchor.AnchorEnum;
import com.ruiysoft.controller.integralmdse.vo.InnrIntegralMdseVo;
import com.ruiysoft.controller.mdse.util.MdseVoUtil;
import com.ruiysoft.controller.mdse.vo.SkuListVo;
import com.ruiysoft.controller.mdse.vo.WxSkuDtoVo;
import com.ruiysoft.entity.mdse.MerchandisePictureSku;
import com.ruiysoft.entity.mdse.MerchandiseRuleValue;
import com.ruiysoft.entity.mdse.MerchandiseRuleValueRela;
import com.ruiysoft.entity.mdse.MerchandiseSku;
import com.ruiysoft.entity.sys.SysMicroShop;
import com.ruiysoft.entity.sys.SysShopPersonnel;
import com.ruiysoft.pub.consts.EnumUtil;
import com.ruiysoft.pub.core.Result;
import com.ruiysoft.pub.core.ResultGenerator;
import com.ruiysoft.pub.entity.PageInfo;
import com.ruiysoft.service.mdse.IMerchandiseManage;
import com.ruiysoft.service.mdse.IMerchandiseSkuService;
import com.ruiysoft.service.mdse.bean.MerchandiseCondition;
import com.ruiysoft.service.mdse.bean.MerchandiseSkuDto;
import com.ruiysoft.service.mdse.consts.MdseEnum;
import com.ruiysoft.service.statistics.IShopUserStatisticsService;
import com.ruiysoft.service.sys.clent.LoginContextUtil;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.*;
import java.util.stream.Collectors;

@javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2018-10-27T01:43:53.483+08:00")

@RestController
public class WxApiController implements WxApi {

    private static final Logger log = LoggerFactory.getLogger(WxApiController.class);

    private final IMerchandiseManage mdseManage;

    private final IShopUserStatisticsService shopUserStatisticsService;

    @Autowired
    private IMerchandiseSkuService skuService;

    @org.springframework.beans.factory.annotation.Autowired
    public WxApiController(IMerchandiseManage mdseManage, IShopUserStatisticsService shopUserStatisticsService) {
        this.mdseManage = mdseManage;
        this.shopUserStatisticsService = shopUserStatisticsService;
    }

    private Long getShopId() {
        SysMicroShop shop = LoginContextUtil.instance().getEntryMicroShop();
        return shop.getId();
    }
    private Long getUserId() {
        SysShopPersonnel personnel = LoginContextUtil.instance().getEntryUser().getPersonnel();
        return personnel.getId();
    }
    private SysShopPersonnel getUser() {
        SysShopPersonnel personnel = LoginContextUtil.instance().getEntryUser().getPersonnel();
        return personnel;
    }

//    @Cacheable(value = "wxMdseDetailSkuIdGet")
    @Override
    @Anchor(anchorType = AnchorEnum.MDSE,skuId = "#skuId")
    public Result<WxSkuDtoVo> wxMdseDetailSkuIdGet(@ApiParam(value = "",required=true) @PathVariable("skuId") Long skuId) {
        Integer mLv = null;

        try{
            SysShopPersonnel personnel = getUser();
            if(Optional.ofNullable(personnel.getMemberFlag()).orElse(false)){
                mLv = personnel.getMemberLevel();
            }

        } catch (Exception e){
            log.error("用户查询商品详情,获取用户信息，skuId--{}",skuId, e);
        }

        try {
            MerchandiseSkuDto skuDto = mdseManage.findMdseSkuDtoBySkuId(skuId);

            InnrIntegralMdseVo innrIntegralMdseVo= null;
            List<Long> skuIds = new ArrayList<>();
            skuIds.add(skuId);
            Map<Long,InnrIntegralMdseVo> innrIntegralMdseVoMap = mdseManage.findIntegralMdseMapBySkuIdsAndMLv(skuIds,mLv == null ? 1 : mLv);
            innrIntegralMdseVo = innrIntegralMdseVoMap.get(skuId);

            return ResultGenerator.genSuccessResult(MdseVoUtil.skuDtoToWxSkuVo(skuDto,innrIntegralMdseVo));

        } catch (Exception e) {
            log.error("用户查询商品详情skuId--{}",skuId, e);
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }

    List<MerchandiseSkuDto> findMdseSkuDtoBySpuId(Long spuId) {
        List<MerchandiseSkuDto> mdseSkuDtoList = new ArrayList<>();
        List<MerchandiseSku> mdseSkuList = skuService.list(new QueryWrapper<MerchandiseSku>().eq("spu_id",spuId).eq("del_flag",0));
        if(mdseSkuList==null||mdseSkuList.size()<=0){
            return null;
        }
        for (MerchandiseSku sku : mdseSkuList) {
            if(sku==null){
                continue;
            }

            MerchandiseSkuDto mdseSkuDto = new MerchandiseSkuDto();
            mdseSkuDto.setSku(sku);
            mdseSkuDtoList.add(mdseSkuDto);
        }
        return mdseSkuDtoList;
    }

//    @Cacheable(value = "wxMdseSkuListGet")
    @Override
    public Result<PageInfo<SkuListVo>> wxMdseSkuListGet(@NotNull @ApiParam(value = "分页开始页", required = true) @Valid @RequestParam(value = "pageStart", required = true) Integer pageStart, @NotNull @ApiParam(value = "每页显示多少条数据", required = true) @Valid @RequestParam(value = "pageSize", required = true) Integer pageSize, @ApiParam(value = "分类id") @Valid @RequestParam(value = "categoryId", required = false) Long categoryId, @ApiParam(value = "商品名") @Valid @RequestParam(value = "mdseName", required = false) String mdseName) {
        Long shopId = getShopId();
        Integer mLv = null;
        MerchandiseCondition condition = new MerchandiseCondition();
        condition.setPageIndex(pageStart);
        condition.setPageSize(pageSize);
        condition.setStatus(MdseEnum.MdseStatus.UP.getIndex());
        condition.setDelFlag(EnumUtil.DelFlag.NO.getIndex());
        condition.setMdseName(mdseName);
        condition.setCategoryId(categoryId);
        condition.setShopId(shopId);

        try{
            SysShopPersonnel personnel = getUser();
            if(Optional.ofNullable(personnel.getMemberFlag()).orElse(false)){
                mLv = personnel.getMemberLevel();
            }

        }catch (Exception e){
            log.error("用户查询商品列表,获取用户信息--{}--{}",shopId, JSONObject.toJSONString(condition), e);
        }

        try {
            PageInfo<MerchandiseSkuDto> page = mdseManage.findSkuDtoPageByCondition(condition);

            // 全部分类下过滤积分类别商品
//            if(categoryId == null) {
//                for (int i = 0; i < page.getList().size(); i++) {
//                    MerchandiseSkuDto merchandiseSkuDto = page.getList().get(i);
//
//                    if (merchandiseSkuDto.getSpu().getMainCategory() == 477)
//                        page.getList().remove(merchandiseSkuDto);
//                }
//            }

            List<SkuListVo> list = new ArrayList<>();
            Map<Long,InnrIntegralMdseVo> innrIntegralMdseVoMap = new HashMap<>();

            List<Long> skuIds = page.getList().stream().map(a->a.getSku().getSkuId()).collect(Collectors.toList());
            innrIntegralMdseVoMap = mdseManage.findIntegralMdseMapBySkuIdsAndMLv(skuIds, mLv == null ? 1 : mLv);

            Map<Long, InnrIntegralMdseVo> finalInnrIntegralMdseVoMap = innrIntegralMdseVoMap;
            page.getList().forEach(skuDto->{
                SkuListVo vo = null;
                try {
                    InnrIntegralMdseVo innrIntegralMdseVo = finalInnrIntegralMdseVoMap.get(skuDto.getSku().getSkuId());

                    if(skuDto.getSpu() != null && skuDto.getSpu().getSpuId() != null) {
                        List<MerchandiseSkuDto> skuDtoList = findMdseSkuDtoBySpuId(skuDto.getSpu().getSpuId());
                        vo = MdseVoUtil.skuDtoToWxSkuListVo(skuDto, innrIntegralMdseVo, skuDtoList);
                        list.add(vo);
                    }

                } catch (Exception e) {
                    log.error("skuDtoToWxSkuVoList--{}",JSONObject.toJSONString(skuDto), e);
                }
            });

            return ResultGenerator.genSuccessResult(new PageInfo<SkuListVo>(list,page));

        } catch (Exception e) {
            log.error("用户查询商品列表--{}--{}",shopId, JSONObject.toJSONString(condition), e);
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }


    @Override
    public Result<Map<Long,SkuListVo>> wxMdseSkuListCSPost(@ApiParam(value = ""  )  @Valid @RequestBody List<Long> skuIds) {
        try {
            List<MerchandiseSkuDto> dtoList = mdseManage.findSkuDtoListByCondition(skuIds);
            List<SkuListVo> list = new ArrayList<>();
            Map<Long,SkuListVo> map = dtoList.stream().map(skuDto->{
                SkuListVo vo = null;
                try {
                    vo = MdseVoUtil.skuDtoToWxSkuListVo(skuDto, null, null);

                } catch (Exception e) {
                    log.error("skuDtoToWxSkuListVo--{}",JSONObject.toJSONString(skuDto), e);
                }
                return vo;
            }).collect(Collectors.toMap(vo->vo.getSkuId(), vo->vo));
            return ResultGenerator.genSuccessResult(map);
        } catch (Exception e) {
            log.error("客服聊天查询商品信息---{}",JSONObject.toJSONString(skuIds), e);
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }
}
